package com.ctshk.rpc.order.scenic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.common.utils.thirdparty.TicketApiUtil;
import com.ctshk.common.utils.thirdparty.airshowReq.*;
import com.ctshk.common.utils.thirdparty.airshowResp.*;
import com.ctshk.common.utils.thirdparty.airshowResp.orderInfo.OrderInfoResp;
import com.ctshk.common.utils.thirdparty.airshowResp.orderInfo.OrderRefundResp;
import com.ctshk.rpc.order.scenic.dto.AirshowOrderAgentListDTO;
import com.ctshk.rpc.order.scenic.dto.AirshowOrderDTO;
import com.ctshk.rpc.order.scenic.dto.AirshowOrderListDTO;
import com.ctshk.rpc.order.scenic.dto.AirshowOrderTouristDTO;
import com.ctshk.rpc.order.scenic.entity.AirshowOrder;
import com.ctshk.rpc.order.scenic.entity.AirshowOrderTicket;
import com.ctshk.rpc.order.scenic.entity.AirshowOrderTourist;
import com.ctshk.rpc.order.scenic.mapper.AirshowOrderMapper;
import com.ctshk.rpc.order.scenic.mapper.AirshowOrderTicketMapper;
import com.ctshk.rpc.order.scenic.mapper.AirshowOrderTouristMapper;
import com.ctshk.rpc.order.scenic.req.*;
import com.ctshk.rpc.order.scenic.service.IAirshowOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.rpc.scenic.dto.AirshowApiSettingDTO;
import com.ctshk.rpc.scenic.dto.AirshowDistributorSettingDTO;
import com.ctshk.rpc.scenic.dto.AirshowProductDTO;
import com.ctshk.rpc.scenic.service.IAirshowApiSettingService;
import com.ctshk.rpc.scenic.service.IAirshowDistributorSettingService;
import com.ctshk.rpc.scenic.service.IAirshowProductService;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 周億耀
 * @since 2021-06-15
 */
@DubboService
public class AirshowOrderServiceImpl extends ServiceImpl<AirshowOrderMapper, AirshowOrder> implements IAirshowOrderService {

    @Autowired
    private AirshowOrderMapper airshowOrderMapper;

    @Autowired
    private AirshowOrderTicketMapper airshowOrderTicketMapper;

    @Autowired
    private AirshowOrderTouristMapper airshowOrderTouristMapper;

    @DubboReference
    private IAirshowDistributorSettingService iAirshowDistributorSettingService;

    @DubboReference
    private IAirshowApiSettingService iAirshowApiSettingService;

    @DubboReference
    private IAirshowProductService iAirshowProductService;

    @Override
    public Result agentCreatePackageOrder(AirshowOrderCreateReq airshowOrderCreateReq, TokenUser tokenUser,Integer source) {

        if(tokenUser == null){
            throw new BusinessException(SystemError.SYS_406);
        }

        if(airshowOrderCreateReq.getProductId() == null){
            throw new BusinessException(SystemError.SYS_409,"产品ID");
        }

        if(StringUtils.isBlank(airshowOrderCreateReq.getProductDate())){
            throw new BusinessException(SystemError.SYS_428,"航展日期");
        }

        if(StringUtils.isBlank(airshowOrderCreateReq.getHotelDateBegin())){
            throw new BusinessException(SystemError.SYS_428,"酒店入住日期");
        }

        if(StringUtils.isBlank(airshowOrderCreateReq.getHotelDateEnd())){
            throw new BusinessException(SystemError.SYS_428,"酒店离店日期");
        }

        if(airshowOrderCreateReq.getTotalNum() == null){
            throw new BusinessException(SystemError.SYS_428,"人数");
        }

        if(airshowOrderCreateReq.getHotelRoomNum() == null){
            throw new BusinessException(SystemError.SYS_428,"房间数");
        }

        Result<AirshowDistributorSettingDTO> distributor = iAirshowDistributorSettingService.getDistributorById(tokenUser.getId());

        AirshowDistributorSettingDTO distributorData = distributor.getData();

        if(distributorData == null
                || distributorData.getBalance().compareTo(new BigDecimal(0)) <= 0){
            throw new BusinessException(SystemError.SCENIC_5021);
        }

        Result<AirshowProductDTO> productById = iAirshowProductService.getProductById(airshowOrderCreateReq.getProductId());

        if(!productById.isSuccess()){
            return productById;
        }

        int hotelStayDays = TicketApiUtil.daysBetween(airshowOrderCreateReq.getHotelDateBegin(), airshowOrderCreateReq.getHotelDateEnd());

        AirshowProductDTO data = productById.getData();

        //如果是港中旅的账号，就用销售价
        if(TicketApiUtil.isCTSHK(tokenUser.getId())){
            data.setAgentPrice(data.getSalePrice());
            data.setTicket_agent_price(data.getTicket_price());
        }

        BigDecimal ticketPrice = data.getTicket_agent_price().multiply(new BigDecimal(airshowOrderCreateReq.getTotalNum()));

        BigDecimal hotelPrice = data.getAgentPrice().multiply(new BigDecimal(hotelStayDays)).multiply(new BigDecimal(airshowOrderCreateReq.getHotelRoomNum()));

        long id = SnowflakeIdWorker.nextId();

        AirshowOrder airshowOrder = EntityUtil.copy(airshowOrderCreateReq, AirshowOrder.class);

        airshowOrder.setId(id);
        airshowOrder.setOrderNumber("H"+id);
        airshowOrder.setProductName(data.getProductName());
        airshowOrder.setOrderType(1);
        airshowOrder.setOrderSource(source);
        airshowOrder.setAccountId(tokenUser.getId());
        airshowOrder.setAccountName(tokenUser.getUsername());
        airshowOrder.setIsDiscount(0);
        airshowOrder.setTotalAmount(ticketPrice.add(hotelPrice));
        airshowOrder.setOrderStatus(0);
        airshowOrder.setOrderTime(LocalDateTime.now());

        //判断余额是否够扣
        if(distributorData.getBalance().compareTo(airshowOrder.getTotalAmount()) < 0){
            throw new BusinessException(SystemError.SCENIC_5021);
        }

        //先扣余额
        Integer i = iAirshowDistributorSettingService.surplusDistributorBalance(tokenUser.getId(), airshowOrder.getTotalAmount());

        if(i <= 0){
            throw new BusinessException(SystemError.SCENIC_5021);
        }

        airshowOrder.setOrderStatus(1);
        airshowOrder.setPayAmount(airshowOrder.getTotalAmount());
        airshowOrder.setPayTime(LocalDateTime.now());
        airshowOrder.setProductIsOut(0);

        airshowOrderMapper.insert(airshowOrder);

        List<AirshowOrderTourist> airshowOrderTourists = EntityUtil.copyList(airshowOrderCreateReq.getTourists(), AirshowOrderTourist.class);

        for(AirshowOrderTourist airshowOrderTourist : airshowOrderTourists){
            airshowOrderTourist.setId(SnowflakeIdWorker.nextId());
            airshowOrderTourist.setOrderId(id);
            airshowOrderTourist.setRealname(airshowOrderTourist.getSurname()+airshowOrderTourist.getName());
            airshowOrderTourist.setAddTime(LocalDateTime.now());
            airshowOrderTourist.setIsDelete(0);

            airshowOrderTouristMapper.insert(airshowOrderTourist);
        }

        Map map = new HashMap();
        map.put("id",id);
        map.put("orderNumber",airshowOrder.getOrderNumber());
        map.put("productName",data.getProductName());
        map.put("productDate",airshowOrderCreateReq.getProductDate());
        map.put("totalNum",airshowOrderCreateReq.getTotalNum());
        map.put("totalHotelRooms",airshowOrderCreateReq.getHotelRoomNum());

        return Result.success(map);
    }

    @Override
    public Result agentCreatePackageOrderNotPay(AirshowOrderCreateReq airshowOrderCreateReq, TokenUser tokenUser, Integer source) {
        if(tokenUser == null){
            throw new BusinessException(SystemError.SYS_406);
        }

        if(airshowOrderCreateReq.getProductId() == null){
            throw new BusinessException(SystemError.SYS_409,"产品ID");
        }

        if(StringUtils.isBlank(airshowOrderCreateReq.getProductDate())){
            throw new BusinessException(SystemError.SYS_428,"航展日期");
        }

        if(StringUtils.isBlank(airshowOrderCreateReq.getHotelDateBegin())){
            throw new BusinessException(SystemError.SYS_428,"酒店入住日期");
        }

        if(StringUtils.isBlank(airshowOrderCreateReq.getHotelDateEnd())){
            throw new BusinessException(SystemError.SYS_428,"酒店离店日期");
        }

        if(airshowOrderCreateReq.getTotalNum() == null){
            throw new BusinessException(SystemError.SYS_428,"人数");
        }

        if(airshowOrderCreateReq.getHotelRoomNum() == null){
            throw new BusinessException(SystemError.SYS_428,"房间数");
        }

        Result<AirshowDistributorSettingDTO> distributor = iAirshowDistributorSettingService.getDistributorById(tokenUser.getId());

        AirshowDistributorSettingDTO distributorData = distributor.getData();

        if(distributorData == null
                || distributorData.getBalance().compareTo(new BigDecimal(0)) <= 0){
            throw new BusinessException(SystemError.SCENIC_5021);
        }

        Result<AirshowProductDTO> productById = iAirshowProductService.getProductById(airshowOrderCreateReq.getProductId());

        if(!productById.isSuccess()){
            return productById;
        }

        int hotelStayDays = TicketApiUtil.daysBetween(airshowOrderCreateReq.getHotelDateBegin(), airshowOrderCreateReq.getHotelDateEnd());

        AirshowProductDTO data = productById.getData();

        //如果是港中旅的账号，就用销售价
        if(TicketApiUtil.isCTSHK(tokenUser.getId())){
            data.setAgentPrice(data.getSalePrice());
            data.setTicket_agent_price(data.getTicket_price());
        }

        BigDecimal ticketPrice = data.getTicket_agent_price().multiply(new BigDecimal(airshowOrderCreateReq.getTotalNum()));

        BigDecimal hotelPrice = data.getAgentPrice().multiply(new BigDecimal(hotelStayDays)).multiply(new BigDecimal(airshowOrderCreateReq.getHotelRoomNum()));

        long id = SnowflakeIdWorker.nextId();

        AirshowOrder airshowOrder = EntityUtil.copy(airshowOrderCreateReq, AirshowOrder.class);

        airshowOrder.setId(id);
        airshowOrder.setOrderNumber("H"+id);
        airshowOrder.setProductName(data.getProductName());
        airshowOrder.setOrderType(1);
        airshowOrder.setOrderSource(source);
        airshowOrder.setAccountId(tokenUser.getId());
        airshowOrder.setAccountName(tokenUser.getUsername());
        airshowOrder.setIsDiscount(0);
        airshowOrder.setTotalAmount(ticketPrice.add(hotelPrice));
        airshowOrder.setOrderStatus(0);
        airshowOrder.setOrderTime(LocalDateTime.now());

        //判断余额是否够扣
        if(distributorData.getBalance().compareTo(airshowOrder.getTotalAmount()) < 0){
            throw new BusinessException(SystemError.SCENIC_5021);
        }

        airshowOrder.setProductIsOut(0);

        airshowOrderMapper.insert(airshowOrder);

        List<AirshowOrderTourist> airshowOrderTourists = EntityUtil.copyList(airshowOrderCreateReq.getTourists(), AirshowOrderTourist.class);

        for(AirshowOrderTourist airshowOrderTourist : airshowOrderTourists){
            airshowOrderTourist.setId(SnowflakeIdWorker.nextId());
            airshowOrderTourist.setOrderId(id);
            airshowOrderTourist.setRealname(airshowOrderTourist.getSurname()+airshowOrderTourist.getName());
            airshowOrderTourist.setAddTime(LocalDateTime.now());
            airshowOrderTourist.setIsDelete(0);

            airshowOrderTouristMapper.insert(airshowOrderTourist);
        }

        Map map = new HashMap();
        map.put("id",id);
        map.put("orderNumber",airshowOrder.getOrderNumber());
        map.put("productName",data.getProductName());
        map.put("productDate",airshowOrderCreateReq.getProductDate());
        map.put("totalNum",airshowOrderCreateReq.getTotalNum());
        map.put("totalHotelRooms",airshowOrderCreateReq.getHotelRoomNum());

        return Result.success(map);
    }


    @Override
    public Result agentPackagePrice(AirshowOrderCreateReq airshowOrderCreateReq, TokenUser tokenUser) {

        if(tokenUser == null){
            throw new BusinessException(SystemError.SYS_406);
        }

        if(airshowOrderCreateReq.getProductId() == null){
            throw new BusinessException(SystemError.SYS_409,"产品ID");
        }

        if(StringUtils.isBlank(airshowOrderCreateReq.getProductDate())){
            throw new BusinessException(SystemError.SYS_428,"航展日期");
        }

        if(StringUtils.isBlank(airshowOrderCreateReq.getHotelDateBegin())){
            throw new BusinessException(SystemError.SYS_428,"酒店入住日期");
        }

        if(StringUtils.isBlank(airshowOrderCreateReq.getHotelDateEnd())){
            throw new BusinessException(SystemError.SYS_428,"酒店离店日期");
        }

        if(airshowOrderCreateReq.getTotalNum() == null){
            throw new BusinessException(SystemError.SYS_428,"人数");
        }

        if(airshowOrderCreateReq.getHotelRoomNum() == null){
            throw new BusinessException(SystemError.SYS_428,"房间数");
        }

        Result<AirshowProductDTO> productById = iAirshowProductService.getProductById(airshowOrderCreateReq.getProductId());

        if(!productById.isSuccess()){
            return productById;
        }

        int hotelStayDays = TicketApiUtil.daysBetween(airshowOrderCreateReq.getHotelDateBegin(), airshowOrderCreateReq.getHotelDateEnd());

        AirshowProductDTO data = productById.getData();

        //如果是港中旅的账号，就用销售价
        if(TicketApiUtil.isCTSHK(tokenUser.getId())){
            data.setAgentPrice(data.getSalePrice());
            data.setTicket_agent_price(data.getTicket_price());
        }

        BigDecimal ticketPrice = data.getTicket_agent_price().multiply(new BigDecimal(airshowOrderCreateReq.getTotalNum()));

        BigDecimal hotelPrice = data.getAgentPrice().multiply(new BigDecimal(hotelStayDays)).multiply(new BigDecimal(airshowOrderCreateReq.getHotelRoomNum()));

//        Map map = new HashMap();
//        map.put("ticketPrice",ticketPrice);
//        map.put("hotelPrice",hotelPrice);
//        map.put("totalPrice",);

        return Result.success(hotelPrice.add(ticketPrice));
    }

    @Override
    @Transactional
    public Result agentCreateAPIOrder(AirshowOrderCreateReq airshowOrderCreateReq, TokenUser tokenUser,Integer source) {

        if(tokenUser == null){
            throw new BusinessException(SystemError.SYS_406);
        }

        if(airshowOrderCreateReq.getTicket_id() == null){
            throw new BusinessException(SystemError.SYS_409,"门票ID");
        }

        if(airshowOrderCreateReq.getScene_id() == null){
            throw new BusinessException(SystemError.SYS_409,"场次ID");
        }

        String sceneName = "";
        String ticketName = "";
        BigDecimal singlePrice = new BigDecimal(0);

        ApiResult<List<TicketResp>> ticket = TicketApiUtil.ticket(airshowOrderCreateReq.getScene_id());

        if(!"10001".equals(ticket.getCode())){
            throw new BusinessException(SystemError.SYS_433,ticket.getMessage());
        }

        Result<AirshowDistributorSettingDTO> distributor = iAirshowDistributorSettingService.getDistributorById(tokenUser.getId());

        AirshowDistributorSettingDTO distributorData = distributor.getData();

        if(distributorData == null
            || distributorData.getBalance().compareTo(new BigDecimal(0)) <= 0){
            throw new BusinessException(SystemError.SCENIC_5019,"余额不足，请先补充余额");
        }

        for(TicketResp ticketResp : ticket.getData()){
            if(String.valueOf(airshowOrderCreateReq.getTicket_id()).equals(ticketResp.getTktId())){

                ticketName = ticketResp.getTicketName();

                //找到对应的票
                if("1".equals(ticketResp.getCheckAge())){
                    //校验年龄

                    for(AirshowOrderTouristReq airshowOrderTouristReq : airshowOrderCreateReq.getTourists()){

                        if(StringUtils.isBlank(airshowOrderTouristReq.getBirthday())){
                            throw new BusinessException(SystemError.SYS_428,"出生日期");
                        }

                        boolean effectiveDate = TicketApiUtil.isEffectiveDate(airshowOrderTouristReq.getBirthday()
                                , ticketResp.getAgeStart(), ticketResp.getAgeEnd());

                        if(effectiveDate){
                            //在区间范围内
                            if("0".equals(ticketResp.getAgeRules())){
                                throw new BusinessException(SystemError.SYS_433,airshowOrderTouristReq.getSurname()+airshowOrderTouristReq.getName()+" 年龄不符合购买条件，无法购买");
                            }
                        }else{
                            //在区间范围外
                            if("1".equals(ticketResp.getAgeRules())){
                                throw new BusinessException(SystemError.SYS_433,airshowOrderTouristReq.getSurname()+airshowOrderTouristReq.getName()+" 年龄不符合购买条件，无法购买");
                            }
                        }
                    }


                }

                long id = SnowflakeIdWorker.nextId();

                AirshowOrder airshowOrder = EntityUtil.copy(airshowOrderCreateReq, AirshowOrder.class);

                airshowOrder.setId(id);
                airshowOrder.setOrderNumber("H"+id);
                airshowOrder.setProductName("【"+sceneName+"】" + ticketResp.getTicketName());
                airshowOrder.setOrderType(0);
                airshowOrder.setOrderSource(source);
                airshowOrder.setAccountId(tokenUser.getId());
                airshowOrder.setAccountName(tokenUser.getUsername());

                //判断是否是优惠票
                if(TicketApiUtil.discountTktIds.contains(ticketResp.getTktId())){
                    airshowOrder.setIsDiscount(1);
                    airshowOrder.setTotalAmount(distributorData.getDiscountPrice().multiply(new BigDecimal(airshowOrderCreateReq.getTotalNum())));
                    singlePrice = distributorData.getDiscountPrice();
                }else{
                    airshowOrder.setIsDiscount(0);
                    airshowOrder.setTotalAmount(distributorData.getNormalPrice().multiply(new BigDecimal(airshowOrderCreateReq.getTotalNum())));
                    singlePrice = distributorData.getNormalPrice();
                }

                //判断余额是否够扣
                if(distributorData.getBalance().compareTo(airshowOrder.getTotalAmount()) < 0){
                    throw new BusinessException(SystemError.SYS_433,"余额不足，无法购买");
                }

                BuyOneTicOrderReq buyOneTicOrderReq = new BuyOneTicOrderReq();
                buyOneTicOrderReq.setFromId(String.valueOf(id));
                buyOneTicOrderReq.setShowId(TicketApiUtil.SHOW_ID);

                List<BuyTicInfo> buyTicInfoList = new ArrayList<>();

                BuyTicInfo buyTicInfo = new BuyTicInfo();
                buyTicInfo.setTicketId(airshowOrderCreateReq.getTicket_id());
                buyTicInfo.setSceneId(airshowOrderCreateReq.getScene_id());
                buyTicInfo.setApplyCount(airshowOrderCreateReq.getTotalNum());
                buyTicInfo.setEnterCount(airshowOrderCreateReq.getTotalNum());

                List<OrderTktInfo> orderTktInfoList = new ArrayList<>();

                for(AirshowOrderTouristReq airshowOrderTouristReq : airshowOrderCreateReq.getTourists()){
                    OrderTktInfo orderTktInfo = new OrderTktInfo();
                    orderTktInfo.setRealname(airshowOrderTouristReq.getSurname()+airshowOrderTouristReq.getName());
                    orderTktInfo.setIdcardType(airshowOrderTouristReq.getIdcardType());
                    orderTktInfo.setIdcardNo(airshowOrderTouristReq.getIdcardNo());
                    orderTktInfoList.add(orderTktInfo);
                }

                buyTicInfo.setOrderTktInfoList(orderTktInfoList);

                buyTicInfoList.add(buyTicInfo);

                buyOneTicOrderReq.setOrderTktList(buyTicInfoList);

                ApiResult<BuyOneTicOrderResp> buyOneTicOrderRespApiResult = TicketApiUtil.buyOneTicOrder(buyOneTicOrderReq);

                if("10001".equals(buyOneTicOrderRespApiResult.getCode())){
                    //购买成功
                    BuyOneTicOrderResp data = buyOneTicOrderRespApiResult.getData();

                    ApiResult<OrderInfoResp> orderInfoRespApiResult = TicketApiUtil.orderInfo(data.getId());

                    sceneName = orderInfoRespApiResult.getData().getOrderTktList().get(0).getSceneName();

                    airshowOrder.setThirdOrderNumber(String.valueOf(data.getId()));

                    //先扣余额
                    Integer i = iAirshowDistributorSettingService.surplusDistributorBalance(tokenUser.getId(), airshowOrder.getTotalAmount());

                    if(i <= 0){
                        throw new BusinessException(SystemError.SYS_433,"余额不足,下单失败");
                    }

                    airshowOrder.setPayTime(LocalDateTime.now());
                    airshowOrder.setPayAmount(airshowOrder.getTotalAmount());
                    airshowOrder.setOrderStatus(1);

                    airshowOrderMapper.insert(airshowOrder);

                    AirshowOrderTicket airshowOrderTicket = new AirshowOrderTicket();
                    airshowOrderTicket.setId(SnowflakeIdWorker.nextId());
                    airshowOrderTicket.setOrderId(id);
                    airshowOrderTicket.setSceneId(Long.valueOf(ticketResp.getSceneId()));
                    airshowOrderTicket.setSceneName(sceneName);
                    airshowOrderTicket.setTicketId(Long.valueOf(ticketResp.getTktId()));
                    airshowOrderTicket.setTicketName(ticketResp.getTicketName());
                    airshowOrderTicket.setTotalNum(airshowOrderCreateReq.getTotalNum());
                    airshowOrderTicket.setEnterNum(airshowOrderCreateReq.getTotalNum());
                    airshowOrderTicket.setIsDelete(0);

                    airshowOrderTicketMapper.insert(airshowOrderTicket);

                    for(AirshowOrderTouristReq airshowOrderTouristReq : airshowOrderCreateReq.getTourists()){

                        AirshowOrderTourist airshowOrderTourist = EntityUtil.copy(airshowOrderTouristReq,AirshowOrderTourist.class);

                        airshowOrderTourist.setId(SnowflakeIdWorker.nextId());
                        airshowOrderTourist.setGroupId(airshowOrderTicket.getId());
                        airshowOrderTourist.setOrderId(id);
                        airshowOrderTourist.setRealname(airshowOrderTourist.getSurname()+airshowOrderTourist.getName());
                        airshowOrderTourist.setIsDelete(0);
                        airshowOrderTourist.setSceneId(airshowOrderTicket.getSceneId());
                        airshowOrderTourist.setTicketId(airshowOrderTicket.getTicketId());

                        airshowOrderTouristMapper.insert(airshowOrderTourist);
                    }

                    Map map = new HashMap();
                    map.put("id",id);
                    map.put("orderNumber",airshowOrder.getOrderNumber());
                    map.put("sceneName",sceneName);
                    map.put("ticketName",ticketName);
                    map.put("singlePrice",singlePrice);
                    map.put("totalNum",airshowOrderCreateReq.getTotalNum());
                    map.put("totalPrice",airshowOrder.getTotalAmount());

                    return Result.success(map);

                }else{
                    throw new BusinessException(SystemError.SYS_433,buyOneTicOrderRespApiResult.getMessage());
                }

            }
        }

        throw new BusinessException(SystemError.SYS_433,"下单失败，未找到该门票");
    }

    @Override
    public Result agentCreateAPIOrderNotPay(AirshowOrderCreateReq airshowOrderCreateReq, TokenUser tokenUser, Integer source) {
        if(tokenUser == null){
            throw new BusinessException(SystemError.SYS_406);
        }

        if(airshowOrderCreateReq.getTicket_id() == null){
            throw new BusinessException(SystemError.SYS_409,"门票ID");
        }

        if(airshowOrderCreateReq.getScene_id() == null){
            throw new BusinessException(SystemError.SYS_409,"场次ID");
        }

        String sceneName = "";
        String ticketName = "";
        BigDecimal singlePrice = new BigDecimal(0);

        ApiResult<List<TicketResp>> ticket = TicketApiUtil.ticket(airshowOrderCreateReq.getScene_id());

        if(!"10001".equals(ticket.getCode())){
            throw new BusinessException(SystemError.SYS_433,ticket.getMessage());
        }

        Result<AirshowDistributorSettingDTO> distributor = iAirshowDistributorSettingService.getDistributorById(tokenUser.getId());

        AirshowDistributorSettingDTO distributorData = distributor.getData();

        if(distributorData == null
                || distributorData.getBalance().compareTo(new BigDecimal(0)) <= 0){
            throw new BusinessException(SystemError.SCENIC_5021);
        }

        for(TicketResp ticketResp : ticket.getData()){
            if(String.valueOf(airshowOrderCreateReq.getTicket_id()).equals(ticketResp.getTktId())){

                ticketName = ticketResp.getTicketName();

                //找到对应的票
                if("1".equals(ticketResp.getCheckAge())){
                    //校验年龄

                    for(AirshowOrderTouristReq airshowOrderTouristReq : airshowOrderCreateReq.getTourists()){

                        if(StringUtils.isBlank(airshowOrderTouristReq.getBirthday())){
                            throw new BusinessException(SystemError.SYS_428,"出生日期");
                        }

                        boolean effectiveDate = TicketApiUtil.isEffectiveDate(airshowOrderTouristReq.getBirthday()
                                , ticketResp.getAgeStart(), ticketResp.getAgeEnd());

                        if(effectiveDate){
                            //在区间范围内
                            if("0".equals(ticketResp.getAgeRules())){
                                throw new BusinessException(SystemError.SYS_433,airshowOrderTouristReq.getSurname()+airshowOrderTouristReq.getName()+" 年龄不符合购买条件，无法购买");
                            }
                        }else{
                            //在区间范围外
                            if("1".equals(ticketResp.getAgeRules())){
                                throw new BusinessException(SystemError.SYS_433,airshowOrderTouristReq.getSurname()+airshowOrderTouristReq.getName()+" 年龄不符合购买条件，无法购买");
                            }
                        }
                    }


                }

                long id = SnowflakeIdWorker.nextId();

                AirshowOrder airshowOrder = EntityUtil.copy(airshowOrderCreateReq, AirshowOrder.class);

                airshowOrder.setId(id);
                airshowOrder.setOrderNumber("H"+id);
                airshowOrder.setProductName("【"+sceneName+"】" + ticketResp.getTicketName());
                airshowOrder.setOrderType(0);
                airshowOrder.setOrderSource(source);
                airshowOrder.setAccountId(tokenUser.getId());
                airshowOrder.setAccountName(tokenUser.getUsername());

                //判断是否是优惠票
                if(TicketApiUtil.discountTktIds.contains(ticketResp.getTktId())){
                    airshowOrder.setIsDiscount(1);
                    airshowOrder.setTotalAmount(distributorData.getDiscountPrice().multiply(new BigDecimal(airshowOrderCreateReq.getTotalNum())));
                    singlePrice = distributorData.getDiscountPrice();
                }else{
                    airshowOrder.setIsDiscount(0);
                    airshowOrder.setTotalAmount(distributorData.getNormalPrice().multiply(new BigDecimal(airshowOrderCreateReq.getTotalNum())));
                    singlePrice = distributorData.getNormalPrice();
                }

                //判断余额是否够扣
                if(distributorData.getBalance().compareTo(airshowOrder.getTotalAmount()) < 0){
                    throw new BusinessException(SystemError.SCENIC_5021);
                }

                airshowOrderMapper.insert(airshowOrder);

                AirshowOrderTicket airshowOrderTicket = new AirshowOrderTicket();
                airshowOrderTicket.setId(SnowflakeIdWorker.nextId());
                airshowOrderTicket.setOrderId(id);
                airshowOrderTicket.setSceneId(Long.valueOf(ticketResp.getSceneId()));
                airshowOrderTicket.setSceneName(sceneName);
                airshowOrderTicket.setTicketId(Long.valueOf(ticketResp.getTktId()));
                airshowOrderTicket.setTicketName(ticketResp.getTicketName());
                airshowOrderTicket.setTotalNum(airshowOrderCreateReq.getTotalNum());
                airshowOrderTicket.setEnterNum(airshowOrderCreateReq.getTotalNum());
                airshowOrderTicket.setIsDelete(0);

                airshowOrderTicketMapper.insert(airshowOrderTicket);

                for(AirshowOrderTouristReq airshowOrderTouristReq : airshowOrderCreateReq.getTourists()){

                    AirshowOrderTourist airshowOrderTourist = EntityUtil.copy(airshowOrderTouristReq,AirshowOrderTourist.class);

                    airshowOrderTourist.setId(SnowflakeIdWorker.nextId());
                    airshowOrderTourist.setGroupId(airshowOrderTicket.getId());
                    airshowOrderTourist.setOrderId(id);
                    airshowOrderTourist.setRealname(airshowOrderTourist.getSurname()+airshowOrderTourist.getName());
                    airshowOrderTourist.setIsDelete(0);
                    airshowOrderTourist.setSceneId(airshowOrderTicket.getSceneId());
                    airshowOrderTourist.setTicketId(airshowOrderTicket.getTicketId());

                    airshowOrderTouristMapper.insert(airshowOrderTourist);
                }

                Map map = new HashMap();
                map.put("id",id);
                map.put("orderNumber",airshowOrder.getOrderNumber());
                map.put("sceneName",sceneName);
                map.put("ticketName",ticketName);
                map.put("singlePrice",singlePrice);
                map.put("totalNum",airshowOrderCreateReq.getTotalNum());
                map.put("totalPrice",airshowOrder.getTotalAmount());

                return Result.success(map);

            }
        }

        throw new BusinessException(SystemError.SYS_433,"下单失败，未找到该门票");
    }

    @Override
    @Transactional
    public Result payOrder(Long id) {

        AirshowOrder airshowOrder = airshowOrderMapper.selectById(id);

        if(airshowOrder == null){
            throw new BusinessException(SystemError.SCENIC_5016);
        }

        if(airshowOrder.getOrderStatus() != 0){
            throw new BusinessException(SystemError.SCENIC_5022);
        }

        Result<AirshowDistributorSettingDTO> distributor = iAirshowDistributorSettingService.getDistributorById(airshowOrder.getAccountId());

        AirshowDistributorSettingDTO distributorData = distributor.getData();

        //判断余额是否够扣
        if(distributorData.getBalance().compareTo(airshowOrder.getTotalAmount()) < 0){
            throw new BusinessException(SystemError.SCENIC_5021);
        }

        if(airshowOrder.getOrderType() == 0){
            //门票

            QueryWrapper<AirshowOrderTicket> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id",airshowOrder.getId());
            AirshowOrderTicket airshowOrderTicket = airshowOrderTicketMapper.selectOne(queryWrapper);

            QueryWrapper<AirshowOrderTourist> wrapper = new QueryWrapper<>();
            wrapper.eq("order_id",airshowOrder.getId());
            List<AirshowOrderTourist> airshowOrderTourists = airshowOrderTouristMapper.selectList(wrapper);

            BuyOneTicOrderReq buyOneTicOrderReq = new BuyOneTicOrderReq();
            buyOneTicOrderReq.setFromId(String.valueOf(id));
            buyOneTicOrderReq.setShowId(TicketApiUtil.SHOW_ID);

            List<BuyTicInfo> buyTicInfoList = new ArrayList<>();

            BuyTicInfo buyTicInfo = new BuyTicInfo();
            buyTicInfo.setTicketId(airshowOrderTicket.getTicketId());
            buyTicInfo.setSceneId(airshowOrderTicket.getSceneId());
            buyTicInfo.setApplyCount(airshowOrder.getTotalNum());
            buyTicInfo.setEnterCount(airshowOrder.getTotalNum());

            List<OrderTktInfo> orderTktInfoList = new ArrayList<>();

            for(AirshowOrderTourist airshowOrderTouristReq : airshowOrderTourists){
                OrderTktInfo orderTktInfo = new OrderTktInfo();
                orderTktInfo.setRealname(airshowOrderTouristReq.getSurname()+airshowOrderTouristReq.getName());
                orderTktInfo.setIdcardType(airshowOrderTouristReq.getIdcardType());
                orderTktInfo.setIdcardNo(airshowOrderTouristReq.getIdcardNo());
                orderTktInfoList.add(orderTktInfo);
            }

            buyTicInfo.setOrderTktInfoList(orderTktInfoList);

            buyTicInfoList.add(buyTicInfo);

            buyOneTicOrderReq.setOrderTktList(buyTicInfoList);

            ApiResult<BuyOneTicOrderResp> buyOneTicOrderRespApiResult = TicketApiUtil.buyOneTicOrder(buyOneTicOrderReq);

            if("10001".equals(buyOneTicOrderRespApiResult.getCode())){
                //购买成功
                BuyOneTicOrderResp data = buyOneTicOrderRespApiResult.getData();

                airshowOrder.setThirdOrderNumber(String.valueOf(data.getId()));

                //先扣余额
                Integer i = iAirshowDistributorSettingService.surplusDistributorBalance(airshowOrder.getAccountId(), airshowOrder.getTotalAmount());

                if(i <= 0){
                    throw new BusinessException(SystemError.SCENIC_5021);
                }

                airshowOrder.setPayTime(LocalDateTime.now());
                airshowOrder.setPayAmount(airshowOrder.getTotalAmount());
                airshowOrder.setOrderStatus(1);

                airshowOrderMapper.updateById(airshowOrder);

                return Result.success(airshowOrder.getId());

            }else{
                throw new BusinessException(SystemError.SYS_433,buyOneTicOrderRespApiResult.getMessage());
            }
        }else if(airshowOrder.getOrderType() == 1){
            //套票

            //先扣余额
            Integer i = iAirshowDistributorSettingService.surplusDistributorBalance(airshowOrder.getAccountId(), airshowOrder.getTotalAmount());

            if(i <= 0){
                throw new BusinessException(SystemError.SCENIC_5021);
            }

            airshowOrder.setOrderStatus(1);
            airshowOrder.setPayAmount(airshowOrder.getTotalAmount());
            airshowOrder.setPayTime(LocalDateTime.now());
            airshowOrder.setProductIsOut(0);

            airshowOrderMapper.updateById(airshowOrder);

            return Result.success(airshowOrder.getId());
        }

        throw new BusinessException(SystemError.SYS_433,"订单类型无法识别");
    }

    @Override
    public Result agentAPIPrice(AirshowOrderAPIPriceReq airshowOrderAPIPriceReq, TokenUser tokenUser) {

        BigDecimal totalAmount = new BigDecimal(0);
        BigDecimal singleAmount = new BigDecimal(0);

        if(tokenUser == null){
            throw new BusinessException(SystemError.SYS_406);
        }

        if(airshowOrderAPIPriceReq.getTicket_id() == null){
            throw new BusinessException(SystemError.SYS_409,"门票ID");
        }

        if(airshowOrderAPIPriceReq.getScene_id() == null){
            throw new BusinessException(SystemError.SYS_409,"场次ID");
        }

        if(airshowOrderAPIPriceReq.getTotalNum() == null){
            throw new BusinessException(SystemError.SYS_409,"总数量");
        }

        ApiResult<List<TicketResp>> ticket = TicketApiUtil.ticket(airshowOrderAPIPriceReq.getScene_id());

        if(!"10001".equals(ticket.getCode())){
            throw new BusinessException(SystemError.SYS_433,ticket.getMessage());
        }

        Result<AirshowDistributorSettingDTO> distributor = iAirshowDistributorSettingService.getDistributorById(tokenUser.getId());

        AirshowDistributorSettingDTO distributorData = distributor.getData();

        if(distributorData == null
                || distributorData.getBalance().compareTo(new BigDecimal(0)) <= 0){
            throw new BusinessException(SystemError.SCENIC_5019,"余额不足，请先补充余额");
        }

        for(TicketResp ticketResp : ticket.getData()){
            if(String.valueOf(airshowOrderAPIPriceReq.getTicket_id()).equals(ticketResp.getTktId())){
                //找到对应的票
                //判断是否是优惠票
                if(TicketApiUtil.discountTktIds.contains(ticketResp.getTktId())){

                    totalAmount = distributorData.getDiscountPrice().multiply(new BigDecimal(airshowOrderAPIPriceReq.getTotalNum()));
                    singleAmount = distributorData.getDiscountPrice();
                }else{

                    totalAmount = distributorData.getNormalPrice().multiply(new BigDecimal(airshowOrderAPIPriceReq.getTotalNum()));
                    singleAmount = distributorData.getNormalPrice();
                }

                Result<AirshowApiSettingDTO> apiSetting = iAirshowApiSettingService.getApiSetting();

                Map map = new HashMap<>();
                map.put("reserveNotice",apiSetting.getData().getReserveNotice());
                map.put("totalPrice",totalAmount);
                map.put("singlePrice",singleAmount);
                map.put("totalNum",airshowOrderAPIPriceReq.getTotalNum());

                return Result.success(map);

            }
        }


        throw new BusinessException(SystemError.SYS_433,"计算价格失败，未找到该门票");
    }

    @Override
    public Result<AirshowOrderDTO> getOrderById(Long id) {

        AirshowOrder airshowOrder = airshowOrderMapper.selectById(id);

        if(airshowOrder == null){
            throw new BusinessException(SystemError.SCENIC_5016);
        }

        QueryWrapper<AirshowOrderTicket> queryTicketGroup = new QueryWrapper<>();
        queryTicketGroup.eq("order_id",airshowOrder.getId());
        queryTicketGroup.eq("is_delete",0);
        AirshowOrderTicket airshowOrderTicket = airshowOrderTicketMapper.selectOne(queryTicketGroup);

        QueryWrapper<AirshowOrderTourist> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",airshowOrder.getId());
        queryWrapper.eq("is_delete",0);

        List<AirshowOrderTourist> airshowOrderTourists = airshowOrderTouristMapper.selectList(queryWrapper);

        List<AirshowOrderTouristDTO> airshowOrderTouristDTOS = EntityUtil.copyList(airshowOrderTourists, AirshowOrderTouristDTO.class);

        AirshowOrderDTO airshowOrderDTO = EntityUtil.copy(airshowOrder, AirshowOrderDTO.class);

        airshowOrderDTO.setTourists(airshowOrderTouristDTOS);

        airshowOrderDTO.setSceneId(airshowOrderTicket.getSceneId());
        airshowOrderDTO.setSceneName(airshowOrderTicket.getSceneName());
        airshowOrderDTO.setTicketId(airshowOrderTicket.getTicketId());
        airshowOrderDTO.setTicketName(airshowOrderTicket.getTicketName());

        return Result.success(airshowOrderDTO);
    }

    @Override
    public Result agentCancelOrderById(AirshowOrderCancelReq airshowOrderCancelReq, TokenUser tokenUser) {

        if(tokenUser == null){
            throw new BusinessException(SystemError.SYS_406);
        }

        AirshowOrder airshowOrder = airshowOrderMapper.selectById(airshowOrderCancelReq.getId());

        if(airshowOrder == null){
            throw new BusinessException(SystemError.SCENIC_5016);
        }

        if(!tokenUser.getId().equals(airshowOrder.getAccountId())){
            throw new BusinessException(SystemError.SCENIC_5019,"订单无权限操作");
        }

        if(airshowOrder.getOrderStatus() == 2){
            throw new BusinessException(SystemError.SCENIC_5019,"订单已在退票申请中，无需重复申请。");
        }

        if(airshowOrder.getOrderStatus() == 3){
            throw new BusinessException(SystemError.SCENIC_5019,"订单已取消，无需重复申请。");
        }

        if(airshowOrder.getOrderType() == 1){
            //查询当前套票产品是否支持退改
            Result<AirshowProductDTO> productById = iAirshowProductService.getProductById(airshowOrder.getProductId());

            AirshowProductDTO data = productById.getData();

            if(data.getCanRefund() != 1){
                throw new BusinessException(SystemError.SYS_433,"当前产品不支持退款");
            }

        }else{

            Result<AirshowDistributorSettingDTO> distributorById = iAirshowDistributorSettingService.getDistributorById(tokenUser.getId());
            airshowOrder.setRefundCharge(distributorById.getData().getRefundServiceCharge());

        }

        airshowOrder.setRefundReason(airshowOrderCancelReq.getRefundReason());
        airshowOrder.setRefundRemark(airshowOrderCancelReq.getRefundRemark());

        if(airshowOrder.getOrderStatus() == 0){
            //订单未付款，直接取消
            airshowOrder.setOrderStatus(3);
            airshowOrder.setCancelTime(LocalDateTime.now());
            airshowOrderMapper.updateById(airshowOrder);

            return Result.success();
        }

        if(airshowOrder.getOrderStatus() == 1){
            //订单已付款，提交到云平台
            airshowOrder.setOrderStatus(2);
            airshowOrder.setCancelTime(LocalDateTime.now());

            Result<AirshowDistributorSettingDTO> distributorById = iAirshowDistributorSettingService.getDistributorById(tokenUser.getId());

            airshowOrder.setRefundCharge(distributorById.getData().getRefundServiceCharge());

            airshowOrderMapper.updateById(airshowOrder);

            return Result.success();
        }

        throw new BusinessException(SystemError.SYS_437);
    }

    @Override
    public Result getAgentOrderListByParams(AirshowOrderListReq airshowOrderListReq, TokenUser tokenUser) {

        if(tokenUser == null){
            throw new BusinessException(SystemError.SYS_406);
        }

        QueryWrapper<AirshowOrder> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(airshowOrderListReq.getProductName())){
            queryWrapper.like("product_name",airshowOrderListReq.getProductName());
        }

        if(StringUtils.isNotBlank(airshowOrderListReq.getOrderNumber())){
            queryWrapper.like("order_number",airshowOrderListReq.getOrderNumber());
        }

        if(StringUtils.isNotBlank(airshowOrderListReq.getMobile())){
            queryWrapper.like("contact_mobile",airshowOrderListReq.getMobile());
        }

        if(airshowOrderListReq.getOrderStatus() != null){
            queryWrapper.eq("order_status",airshowOrderListReq.getOrderStatus());
        }

        if (StringUtils.isNotBlank(airshowOrderListReq.getOrderTimeStart())) {
            queryWrapper.ge("order_time", airshowOrderListReq.getOrderTimeStart() + " 00:00:00");
        }
        //创建结束时间
        if (StringUtils.isNotBlank(airshowOrderListReq.getOrderTimeEnd())) {
            queryWrapper.le("order_time", airshowOrderListReq.getOrderTimeEnd() + " 23:23:59");
        }

        queryWrapper.eq("account_id",tokenUser.getId());

        Page<AirshowOrder> iPage = new Page<>(airshowOrderListReq.getPageNo(), airshowOrderListReq.getPageSize());

        iPage = airshowOrderMapper.selectPage(iPage,queryWrapper);

        List<AirshowOrderAgentListDTO> airshowOrderAgentListDTOS = EntityUtil.copyList(iPage.getRecords(), AirshowOrderAgentListDTO.class);

        PageResponse<AirshowOrderAgentListDTO> result = new PageResponse<>(airshowOrderAgentListDTOS, iPage.getCurrent() == 1,
                iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());

        //查询销售总额
        BigDecimal bigDecimal = airshowOrderMapper.sumSaleAmount(tokenUser.getId());

        Integer integer1 = airshowOrderMapper.sumSaleOrders(tokenUser.getId());

        Result<AirshowDistributorSettingDTO> distributorById = iAirshowDistributorSettingService.getDistributorById(tokenUser.getId());

        Map map = new HashMap();
        map.put("pageResponse",result);
        map.put("totalSaleAmount",bigDecimal);
        map.put("totalOrders",integer1);
        map.put("balance",distributorById.getData().getBalance());

        return Result.success(map);
    }

    @Override
    public Result getPlatformOrderListByParams(AirshowOrderListReq airshowOrderListReq, TokenUser tokenUser) {

        QueryWrapper<AirshowOrder> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(airshowOrderListReq.getProductName())){
            queryWrapper.like("product_name",airshowOrderListReq.getProductName());
        }

        if(StringUtils.isNotBlank(airshowOrderListReq.getOrderNumber())){
            queryWrapper.like("order_number",airshowOrderListReq.getOrderNumber());
        }

        if(StringUtils.isNotBlank(airshowOrderListReq.getMobile())){
            queryWrapper.like("contact_mobile",airshowOrderListReq.getMobile());
        }

        if(airshowOrderListReq.getOrderStatus() != null){
            queryWrapper.eq("order_status",airshowOrderListReq.getOrderStatus());
        }

        if (StringUtils.isNotBlank(airshowOrderListReq.getOrderTimeStart())) {
            queryWrapper.ge("order_time", airshowOrderListReq.getOrderTimeStart() + " 00:00:00");
        }
        //创建结束时间
        if (StringUtils.isNotBlank(airshowOrderListReq.getOrderTimeEnd())) {
            queryWrapper.le("order_time", airshowOrderListReq.getOrderTimeEnd() + " 23:23:59");
        }

        Page<AirshowOrder> iPage = new Page<>(airshowOrderListReq.getPageNo(), airshowOrderListReq.getPageSize());

        iPage = airshowOrderMapper.selectPage(iPage,queryWrapper);

        List<AirshowOrderListDTO> airshowOrderListDTOS = EntityUtil.copyList(iPage.getRecords(), AirshowOrderListDTO.class);

        PageResponse<AirshowOrderListDTO> result = new PageResponse<>(airshowOrderListDTOS, iPage.getCurrent() == 1,
                iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());


        Map map = new HashMap();
        map.put("pageResponse",result);

        return Result.success(map);
    }

    @Override
    public Result platformCancelOrderById(AirshowOrderCancelReq airshowOrderCancelReq, TokenUser tokenUser) {

        AirshowOrder airshowOrder = airshowOrderMapper.selectById(airshowOrderCancelReq.getId());

        if(airshowOrder == null){
            throw new BusinessException(SystemError.SCENIC_5016);
        }

        if(airshowOrder.getOrderStatus() == 2){
            throw new BusinessException(SystemError.SCENIC_5019,"订单已在退票申请中，无需重复申请。");
        }

        if(airshowOrder.getOrderStatus() == 3){
            throw new BusinessException(SystemError.SCENIC_5019,"订单已取消，无需重复申请。");
        }

        if(airshowOrder.getOrderType() == 1){
            //查询当前套票产品是否支持退改
            Result<AirshowProductDTO> productById = iAirshowProductService.getProductById(airshowOrder.getProductId());

            AirshowProductDTO data = productById.getData();

            if(data.getCanRefund() != 1){
                throw new BusinessException(SystemError.SYS_433,"当前产品不支持退款");
            }

        }else{

            Result<AirshowDistributorSettingDTO> distributorById = iAirshowDistributorSettingService.getDistributorById(airshowOrder.getAccountId());
            airshowOrder.setRefundCharge(distributorById.getData().getRefundServiceCharge());

        }

        airshowOrder.setRefundReason(airshowOrderCancelReq.getRefundReason());
        airshowOrder.setRefundRemark(airshowOrderCancelReq.getRefundRemark());

        if(airshowOrder.getOrderStatus() == 0){
            //订单未付款，直接取消
            airshowOrder.setOrderStatus(3);
            airshowOrder.setCancelTime(LocalDateTime.now());
            airshowOrderMapper.updateById(airshowOrder);

            return Result.success();
        }

        if(airshowOrder.getOrderStatus() == 1){
            //订单已付款，提交到云平台
            airshowOrder.setOrderStatus(2);
            airshowOrder.setCancelTime(LocalDateTime.now());

            Result<AirshowDistributorSettingDTO> distributorById = iAirshowDistributorSettingService.getDistributorById(tokenUser.getId());

            airshowOrder.setRefundCharge(distributorById.getData().getRefundServiceCharge());

            airshowOrderMapper.updateById(airshowOrder);

            return Result.success();
        }

        throw new BusinessException(SystemError.SYS_437);
    }

    @Override
    public Result platformHandleOrderApply(AirshowOrderCancelHandleReq airshowOrderCancelHandleReq) {

        AirshowOrder airshowOrder = airshowOrderMapper.selectById(airshowOrderCancelHandleReq.getId());

        if(airshowOrder == null){
            throw new BusinessException(SystemError.SCENIC_5016);
        }

        if(airshowOrderCancelHandleReq.getStatus() == null){
            throw new BusinessException(SystemError.SYS_428,"是否同意");
        }

        if(airshowOrder.getOrderStatus() == 2){


            if(airshowOrderCancelHandleReq.getStatus() == 1){
                //同意
                if(airshowOrder.getOrderType() == 0){
                    //门票

                    //退票进行中（API方处理中）
                    airshowOrder.setOrderStatus(4);

                    ApiResult<OrderRefundResp> apiResult = TicketApiUtil.refundByOrderNumber(airshowOrder.getThirdOrderNumber());

                    //TODO 从API里获取到退款第三方服务费，以及应退款金额
                    airshowOrder.setRefundAmount(new BigDecimal(apiResult.getData().getChargingAmount()));

                    airshowOrderMapper.updateById(airshowOrder);

                    return Result.success();
                }else{
                    //套票
                    if(airshowOrderCancelHandleReq.getRefundAmount() == null){
                        throw new BusinessException(SystemError.SYS_433,"实退金额为空");
                    }

                    airshowOrder.setOrderStatus(3);
                    airshowOrder.setRefundAmount(airshowOrderCancelHandleReq.getRefundAmount());

                    airshowOrderMapper.updateById(airshowOrder);

                    return Result.success();
                }
            }else{
                //拒绝
                airshowOrder.setOrderStatus(1);
                airshowOrderMapper.updateById(airshowOrder);

                return Result.success();
            }

        }else{
            throw new BusinessException(SystemError.SYS_433,"当前订单状态无法操作");
        }

    }

    @Override
    public Result autoCheckAPIOrder() {

        RefundListReq refundListReq = new RefundListReq();
        refundListReq.setPage(1);
        refundListReq.setSize(20);

        //总共有多少个退款成功的
        int i = 0;

        ListApiResult<RefundListResp> refundListRespListApiResult = TicketApiUtil.finishedList(refundListReq);

        for(RefundListResp refundListResp : refundListRespListApiResult.getList()){

            QueryWrapper<AirshowOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("third_order_number",refundListResp.getId());

            AirshowOrder airshowOrder = airshowOrderMapper.selectOne(queryWrapper);

            if(airshowOrder != null){
                if(airshowOrder.getOrderStatus() == 4){
                    if("退票成功".equals(refundListResp.getState())){
                        airshowOrder.setOrderStatus(3);
                        //todo 退票成功，返还余额
                        if(airshowOrder.getRefundAmount() != null){
                            iAirshowDistributorSettingService.addDistributorBalance(airshowOrder.getAccountId(),airshowOrder.getRefundAmount());
                            i++;
                        }

                    }else{
                        airshowOrder.setOrderStatus(1);
                    }

                    airshowOrderMapper.updateById(airshowOrder);
                }
            }
        }

        return Result.success(i);
    }

}
